<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
    <script src="/vue.js" type="text/javascript"></script>
    <script src="/axios.min.js" type="text/javascript"></script>
</head>
<body>

    <div id="root">
        <h1>{{isLogining?'正在授权请稍后.......':'登陆成功！！！！'}}</h1>
        <button @click="toAuthorize" v-if="!isClicked">去授权</button>

    </div>

</body>

<script>
    new Vue({
        el:"#root",
        data:{
            isLogining:true,
            key:'',
            timer:"",
            isClicked:false,
            loginResult:{},
            params:{},
            href:"http://passport.51xuecheng.cn:8080/oauth2/authorize?accessToken=79daad3a47475954a03ef1746035a6f0&state="
        },
        methods:{
            getKey(){
                if(this.key);
                axios.get('/login/key')
                    .then( (response)=> {
                        // handle success
                        console.log(response.data.data)
                        this.key=response.data.data
                        console.log(this.key)
                    })
                    .catch(function (error) {
                        // handle error
                        console.log(error);
                    })
                    .finally(function () {
                        // always executed
                    });
            },
            checkLoginStatus(){
                console.log("checkLoginStatus:",this.key)
                if(!this.key)return;
                axios.get("/login/user?state="+this.key)
                    .then(res=>{
                        console.log(res.data)
                        this.loginResult=res.data.data
                        if(this.loginResult){
                            clearInterval(this.timer)
                            this.isLogining=false
                        }
                    })
            },
            toAuthorize(){
                console.log("toAuthorize",this.key)
                if(!this.key)return;
                this.isClicked=true
                window.open(this.href+this.key)
            },
            getQueryParam(){
                let params = {}
                let url = window.location.search
                if (url.indexOf('?') !== -1) {

                    let arr = url.split('?')[1].split('&')

                    arr.forEach((item) => {

                        let val = item.split('=')

                        params[val[0]] = val[1]

                    })
                    this.params=params
                }

                if(this.params.state){
                    this.key=this.params.state;
                }
            }

        },



        mounted(){
            this.getQueryParam()
            this.getKey()
            this.timer=setInterval(()=>{
                this.checkLoginStatus()
            },1000)
        }
    })
</script>
</html>